import json
import os

class AliyunConfig:
    """阿里云配置管理类"""
    
    def __init__(self):
        self.config_dir = os.path.join(os.path.dirname(__file__), 'config', 'aliyun')
        self._account_config = None
        self._devices_config = None
        self._load_configs()
    
    def _load_configs(self):
        """加载所有配置文件"""
        try:
            # 加载账号配置
            account_path = os.path.join(self.config_dir, 'account.json')
            with open(account_path, 'r', encoding='utf-8') as f:
                self._account_config = json.load(f)
            
            # 加载设备配置
            devices_path = os.path.join(self.config_dir, 'devices.json')
            with open(devices_path, 'r', encoding='utf-8') as f:
                self._devices_config = json.load(f)
                
            print("✅ 阿里云配置加载成功")
            
        except Exception as e:
            print(f"❌ 配置加载失败: {e}")
            raise
    
    @property
    def access_key_id(self):
        if self._account_config is None:
            raise Exception("账号配置未加载")
        return self._account_config['account']['accessKeyId']
    
    @property
    def access_key_secret(self):
        if self._account_config is None:
            raise Exception("账号配置未加载")
        return self._account_config['account']['accessKeySecret']
    
    @property
    def region(self):
        if self._account_config is None:
            raise Exception("账号配置未加载")
        return self._account_config['region']
    
    @property
    def endpoint(self):
        if self._account_config is None:
            raise Exception("账号配置未加载")
        return self._account_config['endpoint']
    
    @property
    def instance_id(self):
        if self._devices_config is None:
            raise Exception("设备配置未加载")
        return self._devices_config['instanceId']
    
    def get_device_config(self, device_id):
        """根据设备ID获取设备配置"""
        if self._devices_config is None:
            raise Exception("设备配置未加载")
        for device in self._devices_config['devices']:
            if device['id'] == device_id:
                return device
        return None
    
    def get_all_devices(self):
        """获取所有设备配置"""
        if self._devices_config is None:
            raise Exception("设备配置未加载")
        return self._devices_config['devices']
    
    def get_device_by_name(self, device_name):
        """根据设备名称获取设备配置"""
        if self._devices_config is None:
            raise Exception("设备配置未加载")
        for device in self._devices_config['devices']:
            if device['DeviceName'] == device_name:
                return device
        return None

# 全局配置实例
aliyun_config = AliyunConfig()
